package com.wm.blog_admin.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wm.blog_admin.dao.TCommentDAO;
import com.wm.blog_admin.domain.CommentDo;
import com.wm.blog_admin.query.TCommentQuery;
import com.wm.blog_common.base.BeanUtils;
import com.wm.blog_common.bean.QueryPage;
import com.wm.blog_common.domain.TCommentDO;
import com.wm.blog_common.entity.TComment;
import com.wm.blog_common.entity.TFile;
import com.wm.blog_common.result.Result;
import com.wm.picture_interface.feign.PictureFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author 半卷流年
 * @since 2020-03-24
 */
@Service
@Slf4j
public class TCommentService{
    @Autowired
    private TCommentDAO tCommentDAO;

    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Autowired
    private ThreadPoolTaskExecutor poolTaskExecutor;

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public Result<TCommentDO> selectById(Long id){
        return Result.success(BeanUtils.copyProperties(tCommentDAO.getById(id),TCommentDO.class));
    }

    /**
    * 根据ID删除
    * @param id
    * @return
    */
    public Result deleteById(Long id){
        return tCommentDAO.removeById(id)?Result.success():Result.failure();
    }

    /**
    * 添加
    * @param tComment
    * @return
    */
    public Result insert(TComment tComment){
        return tCommentDAO.save(tComment)?Result.success():Result.failure();
    }

    /**
    * 修改
    * @param tComment
    * @return
    */
    public Result update(TComment tComment){
        return tCommentDAO.updateById(tComment)?Result.success():Result.failure();
    }

    /**
    * 统计总数
    *
    * @param query
    * @return
    */
    public Result<Integer> count(TCommentQuery query) {
        return Result.success(tCommentDAO.count(this.combineQuery(query)));
    }

    /**
    * 列表查询
    * @param query
    * @return
    */
    public Result<List<TCommentDO>> list(TCommentQuery query){
        return Result.success(BeanUtils.copyListProperties(tCommentDAO.list(this.combineQuery(query)),TCommentDO.class));
    }
    /**
    * 分页查询
    * @param page
    * @return
    */
    public Result<Page<CommentDo>> page(QueryPage page, TCommentQuery query){
        Result<Page<CommentDo>> result = tCommentDAO.pageList(page, query);
        if(result.isSuccess() && !ObjectUtils.isEmpty(result.getData()) && !CollectionUtils.isEmpty(result.getData().getRecords())){
            List<CommentDo> records = result.getData().getRecords();
            List<Long> fileIdList = records.stream()
                    .filter(x -> !ObjectUtils.isEmpty(x) && !ObjectUtils.isEmpty(x.getFileId()))
                    .map(CommentDo::getFileId).distinct()
                    .collect(Collectors.toList());
            // k:fileId v:file url
            Map<Long, String> map = new HashMap<>();
                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            if(!CollectionUtils.isEmpty(fileIdList)){
            //异步调用feign
                    Result<List<TFile>> listResult = pictureFeignClient.getByIdList(fileIdList);
                    if (listResult.isSuccess() && !CollectionUtils.isEmpty(listResult.getData())) {
                        Map<Long, String> stringMap = listResult.getData().stream().collect(Collectors.toMap(TFile::getId, TFile::getPicUrl));
                        map.putAll(stringMap);
                    }
            }
        }, poolTaskExecutor);
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
               log.error("异步请求feign异常:[{}]",e.getMessage(),e);
            }
            List<CommentDo> resultList = records.stream().peek(item -> {
                item.setPicUrl(map.getOrDefault(item.getFileId(), null));
            }).collect(Collectors.toList());
            result.getData().setRecords(resultList);
        }
        return result;
    }

    /**
    * 组装查询条件
    *
    * @param query
    * @return
    */
    private QueryWrapper<TComment> combineQuery(TCommentQuery query) {
        QueryWrapper<TComment> wrapper = new QueryWrapper<>();
        //todo 查询条件 wrapper.eq("字段名","值")
        return wrapper;
    }

}







